<template>
  <div class="flex flex-col items-center justify-center gap-4 p-4">
    <button class="btn btn-soft btn-primary" @click="uploadFile">
      <template v-if="load">
        <span class="loading loading-spinner loading-primary"></span>
        上传中...
      </template>
      <div v-else class="flex items-center gap-2">
        <ArrowUpTray class="size-4" :fontControlled="false" />
        <span>请上传知识库文件</span>
      </div>
    </button>
    <div class="w-[60%] max-w-[800px] rounded-box border border-base-content/5 bg-base-100">
      <table class="table">
        <!-- head -->
        <thead class="bg-base-200">
          <tr>
            <th>序号</th>
            <th>知识库名称</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <!-- row 2 -->
          <tr
            v-for="(filename, rowIndex) of knowledgeList"
            :key="rowIndex"
            class="hover:bg-base-300"
          >
            <th>{{ rowIndex < 10 ? "0" + (rowIndex + 1) : rowIndex + 1 }}</th>
            <td>{{ filename }}</td>
            <td>
              <button class="btn btn-soft btn-error" @click="deleteKnowledge(filename)">
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <Toast v-model:msg="toast.message" :status="toast.status" />
  </div>
</template>

<script setup>
import { ref } from "vue";
import ArrowUpTray from "@/assets/icons/arrow-up-tray.svg";
import Toast from "@/components/toast";
import { getFileList } from "~/apis/index.server";
import { uploadFile as uploadFileApi, deleteFile } from "~/apis/index.client";

const { data: knowledgeList = [] } = await getFileList();
const load = ref(false);
const toast = ref({
  message: "",
  status: "success",
});

const uploadFile = () => {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = ".txt,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx";
  input.click();

  input.onchange = async () => {
    const file = input.files[0];
    load.value = true;
    try {
      await uploadFileApi(file);
      load.value = false;
      toast.message = "上传成功！";
      toast.status = "success";
      await resetTableDataCache();
    } catch (error) {
      load.value = false;
      toast.value.message = "上传失败！";
      toast.value.status = "error";
    }
  };
};

const resetTableDataCache = async () => {
  const { data, refresh } = await getFileList();
  await refresh();
  knowledgeList.value = data.value;
};

const deleteKnowledge = async (filename) => {
  try {
    await deleteFile(filename);
    await resetTableDataCache();
    toast.value.message = "删除成功！";
    toast.value.status = "success";
  } catch (error) {
    toast.value.message = "删除失败！";
    toast.value.status = "error";
  }
};
</script>
